﻿/*var base= document.getElementById("base").href;*/
/*$._getDicByCode("ZSK00", "dicData");*/
var d = $("#dicData").val();
var pageType = $("#pageType").val(); // 页面类型， 1-填报，2-查询
(function(window, $, undefined) {
    if (window.comprehensive == undefined) {
        window.comprehensive = {};
    }

    window.comprehensive.knowledge = {

        data: {
            params: {}
        },
        init: function() {
            //App.init(); // initlayout and core plugins
            this.initData();
            this.bindEvent();
            this.initTable();
            this.bindTableEvent();
            this.initZTree();
        },
        initData: function(){
        },
        bindEvent: function() {
            //点击来源单位选择
            $("#add-reaportOrganId-text").click(function () {
                $("#add-reaportOrganId-select-tree").toggle();
                return false;
            });

            $("#type").val("").select2({ data : [{id:"1", text:"1"},{id:"2", text:"2"},{id:"3", text:"3"},{id:"", text:"请选择"}], allowClear : true });
            $("#start").val("").select2({ data : [{id:"1", text:"已上报"},{id:"0", text:"未上报"},{id:"", text:"请选择"}], allowClear : true });
            $("#industry").val("").select2({ data : [{id:"0", text:"xxx"}], allowClear : true });
            $("#knowledge_add_btn").click(function() {window.location.href="/safely/comprehensive/emenous/add";return false;});


            if (pageType == 2) {  // //pageType 页面类型， 1-填报，2-查询
                $("#reception").click();
            }
            if (pageType == 1) {  //
                $("#submission").click();
            }
            $("#reception").click(function () {
                $("#pageType").val(2);
                pageType = 2;
                window.location.href = "/safely/comprehensive/emenous/main?pageType=2";
            });
            $("#submission").click(function () {
                $("#pageType").val(1);
                pageType = 1;
                window.location.href =  "/safely/comprehensive/emenous/main?pageType=1";
                //findMyPage();
            });

        },
        getParams: function(){
            var o = {};
            var a = $(".form-horizontal").serializeArray();
            $.each(a, function() {
                if (o[this.name]) {
                    if (!o[this.name].push) {
                        o[this.name] = [o[this.name]];
                    }
                    o[this.name].push(this.value || '');
                } else {
                    o[this.name] = this.value || '';
                }
            });
            /*         alert(JSON.stringify(a));*/
            this.data.params=o;
            return this.data.params ;

            // alert(JSON.stringify(this.data.params));
        },
        zTreeSetting: {
            async: {
                enable: true,
                contentType: "application/json",
                type: "get",
                url:  "/safely/system/organ/selectChildrensById.html?id=1"
            },
            simpleData: {
                enablue: true,
                idKey: "id"
            },
            view: {
                selectedMulti: false
            },
            edit: {
                enable: false,
                showRemoveBtn: true,
                showRenameBtn: true
            },
            data: {
                simpleData: {
                    enable: true
                }
            },
            callback: {
                beforeDrag: function () {
                    return false;
                }, // 取消拖拽
                onClick: zTreeOnClick
            }
        },
        initZTree: function () {

            /*来源单位下拉选择*/
            $.fn.zTree.init($("#add-reaportOrganId-select-tree"), this.zTreeSetting);
            $("#add-reaportOrganId-select-tree").attr("style", "width:100%;min-height:300px;overflow-y:auto;overflow-x:auto;display:none;position:absolute;z-index:1000;");

        },
        initTable: function() {
            var me = this;
            me.getParams();
            this.data.table = $("#knowledge-table").intBootstrapTable({
                url: '/safely/comprehensive/emenous/list',
                queryParams: function(params){
                    params["params"] = JSON.stringify(me.data.params);
                    return params;
                },
                clickToSelect: true,
                singleSelect: false,
                checkboxHeader: true,
                selectItemName: "id",
                toolbar: "#knowledge-toolbar",
                columns: [
                    {field: 'id', title: '序号', align: 'center', formatter: function (value, row, index) {
                        return $("#knowledge-table").getIndex(index);
                    },valign: 'middle', width: "5%"},
                    {field: 'title', title: '标题', align: 'center', valign: 'middle', width: "10%"},
                    {field: 'type', title: '类型代码', formatter: function (value, row, index) {
                        if(value!=null){ return JSON.parse($._findDic(value, d)).name;}else {
                            return "";
                        }
                    },align: 'center', valign: 'middle', width: "8%"},
                    {field: 'theme', title: '主题词', align: 'center', valign: 'middle', width: "8%"},
                    {field: 'comAbstract', title: '摘要', align: 'center', valign: 'middle', width: "8%"},
                    {field: 'sourceNous', title: '来源', align: 'center', valign: 'middle', width: "8%"},
                    {field: 'organname', title: '来源单位', align: 'center', valign: 'middle', width: "5%"},
                    {field: 'updateTime', title: '更新时间',formatter:function(value,row,index){return changeDateFormat(value)}, align: 'center', valign: 'middle', width: "8%"},
                    {field: 'remark', title: '备注', align: 'center', valign: 'middle', width: "5%"},
                    {field: 'status', title: '上报状态', align: 'center', valign: 'middle', formatter:function(value,row,index){
                        if(value==0)
                            return "未上报";
                        if(value==1)
                            return "已上报";

                    },width: "5%"},
                    {field: 'settings', title: '操作', align: 'center', valign: 'middle', width: "25%", events: this.operateEvents, formatter: this.addFunctionAlty}
                ],
                detailView : false
            });
        },
        operateEvents : { // 添加一个按钮组在对应的按钮组中写下需要使用的事件
            "click #knowledge-table-delete" : function(e, value, row, index) { // 删除按钮事件
                $.confirmDel("确定删除？", function() {

                    row.isDelDicId=1;
                    $.post("/safely/comprehensive/emenous/update",row,function(flag){
                        if(flag){
                            $.alert("删除成功");
                            window.comprehensive.knowledge.refreshTable();
                        }else {
                            $.alert("删除失败");
                        }
                    })
                })

            },
            "click #knowledge-table-link" : function(e, value, row, index) { // 上报按钮事件
                $.confirmDel("您确定要上报信息吗？", function() {

                    row.status=1;

                    $.post("/safely/comprehensive/emenous/update",row,function(flag) {
                        if (flag) {
                            $.alert("上报成功");
                            window.comprehensive.knowledge.refreshTable();
                        } else {
                            $.alert("上报失败");
                        }
                    })
                })

            },
            "click #knowledge-table-edit" : function(e, value, row, index) { // 编辑按钮事件

                window.location.href="/safely/comprehensive/emenous/edit?id="+row.id;
            },
            "click #knowledge-table-show" : function(e, value, row, index) { // 查看按钮事件

                window.location.href="/safely/comprehensive/emenous/show?id="+row.id;
            }
        },
        addFunctionAlty : function(value, row, index) { // 把需要创建的按钮封装在函数中
            if(pageType == 1){ // pageType页面类型， 1-填报，2-查询
                var dis;
                if(row.status==1){
                    dis='disabled="disabled"';
                }
                return ['<button type="button" class="btn btn-sm btn-info" id="knowledge-table-link"'+dis+'>上报</button>',
                    '<button class="btn btn-sm btn-success" id="knowledge-table-show" style="margin-left:5px;margin-right:5px;">查看</button>',
                    '<button class="btn btn-sm btn-success" id="knowledge-table-edit" '+dis+'style="margin-left:5px;margin-right:5px;" '+dis+'>编辑</button>',
                    '<button class="btn btn-sm btn-danger" id="knowledge-table-delete" style="margin-left:5px;margin-right:5px;" '+dis+'>删除</button>'].join("")
            }else if(pageType == 2){ // pageType页面类型， 1-填报，2-查询  查询只有查看按钮
                return ['<button class="btn btn-sm btn-success" id="knowledge-table-show" style="margin-left:5px;margin-right:5px;">查看</button>'].join("")
            }
        },
        refreshTable: function() {
            this.getParams();
            this.data.table.bootstrapTable("refresh");
        },
        bindTableEvent: function(){

        }
    };
    //转换日期格式(时间戳转换为datetime格式)
    function changeDateFormat(cellval) {
        var dateVal = cellval + "";
        if (cellval != null) {
            var date = new Date(parseInt(dateVal.replace("/Date(", "").replace(")/", ""), 10));
            var month = date.getMonth() + 1 < 10 ? "0" + (date.getMonth() + 1) : date.getMonth() + 1;
            var currentDate = date.getDate() < 10 ? "0" + date.getDate() : date.getDate();
            var hours = date.getHours() < 10 ? "0" + date.getHours() : date.getHours();
            var minutes = date.getMinutes() < 10 ? "0" + date.getMinutes() : date.getMinutes();
            var seconds = date.getSeconds() < 10 ? "0" + date.getSeconds() : date.getSeconds();
            return date.getFullYear() + "-" + month + "-" + currentDate + " " + hours + ":" + minutes + ":" + seconds;
        }
    }


    $("#search_btn").click(function () {
        window.comprehensive.knowledge.refreshTable();
    });
    $("#edit_btn_knowledge").click(function () {
        //window.comprehensive.criterion.data.params=$(".form-horizontal").serializeObject();
        //  window.comprehensive.criterion.refreshTable();
        // alert(JSON.stringify(window.comprehensive.criterion.data.params));
        window.location.href="/safely/comprehensive/emenous/ExportExcel?"+$(".form-horizontal").serialize();
    });
    if($("#hiddenFlag").val()=="fail"){
        $("#hiddenFlag").value="success";
        $.alert("当前条件查询到内容为空，无法生成Excel表格");
    }
    window.comprehensive.knowledge.init();
    /*var data = {total : "200", rows : [{id : "159851555555555588", name : "xxx" , type : "xxx", time : "xxx", location : "xxx", company : "xxx", status : "xxx"},{id : "1", name : "xxx" , type : "xxx", time : "xxx", location : "xxx", company : "xxx", status : "xxx"}]};
     $("#knowledge-table").bootstrapTable("load", data);*/
    $._showDic("ZSK00", "dic", "类型代码");
})(window, $, undefined);

function zTreeOnClick(event, treeId, treeNode) {// 点击zTree事件
    if (treeNode.level == 2 || treeNode.level == 1) {
        //alert("点击");
    }

    /*来源单位下拉选择*/
    if (treeId == 'add-reaportOrganId-select-tree') {
        $("#add-reaportOrganId-text").val(treeNode.name);
        $("#reaportOrganId").val(treeNode.id);
        $("#add-reaportOrganId-text").click(); // 选中后触发重新点击事件关闭树
    }
}

// 根据id获取机构信息
function getOrgan(organId) {
    var date;
    $.ajax({
        type: "get",
        url:   "/safely/system/organ/selectById?id=" + organId,
        //data:$(".form-horizontal").serialize(),
        dataType: "json",
        async: false, // 同步
        success: function (organ) {
            if (organ != null) {
                date = organ;
            } else {
                console.log('获取数据为null');
                //alert('获取数据失败');
            }
        },
        error: function () {
            console.log('获取数据失败');
            //alert('获取数据失败');
        }
    })
    return date;
}